package com.echo.im.domain.message;

import com.echo.im.client.handler.PushMessageHandler;
import com.echo.im.client.model.IMMessage;
import com.echo.im.client.model.IMPlatformMessage;
import com.echo.im.client.model.IMUserInfo;
import com.echo.im.client.model.PlatformMessageVO;
import com.echo.im.common.contant.Command;
import com.echo.im.common.model.RecvInfo;
import com.echo.im.common.model.UserInfo;
import com.echo.im.infrastructure.mq.event.model.push.PushMessageEvent;
import com.echo.im.infrastructure.mq.event.producer.EventPublisher;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: echo
 * @time: 2024-08-25
 */
@Component
@RequiredArgsConstructor
public class DefualtPushMessageHandler implements PushMessageHandler {

    private final PushMessageEvent pushMessageEvent;
    private final EventPublisher eventPublisher;


    @Override
    public void pushMessage(IMMessage message, List<IMUserInfo> receivers, String serverId,Boolean needOfflineStore) {

        RecvInfo recvInfo = new RecvInfo<>();
        recvInfo.setSender(new UserInfo(message.getSender().getId(),message.getSender().getTerminal()));
        List<UserInfo> list = receivers.stream().map((receiver) -> new UserInfo(receiver.getId(), receiver.getTerminal())).toList();
        recvInfo.setReceivers(list);
        recvInfo.setData(message.getData());
        recvInfo.setCommand(message.getCmd());
        recvInfo.setNeedOfflineStore(message.getIsNeedOfflineStore());
        //发送给自己的消息不需要离线存储
        recvInfo.setNeedOfflineStore(needOfflineStore);
        eventPublisher.publishWithServerId(pushMessageEvent,recvInfo,serverId);
    }

    @Override
    public void pushPlatformMessage(IMPlatformMessage message, List<IMUserInfo> receivers, String serveId) {
        RecvInfo<PlatformMessageVO> recvInfo = new RecvInfo<>();
        List<UserInfo> list = receivers.stream().map((receiver) -> new UserInfo(receiver.getId(), receiver.getTerminal())).toList();
        recvInfo.setReceivers(list);
        recvInfo.setData(message.getData());
        recvInfo.setCommand(Command.PLATFORM_MESSAGE);

        eventPublisher.publishWithServerId(pushMessageEvent,recvInfo,serveId);
    }
}
